package com.example.yoga.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yoga.entity.Announcement;
import com.example.yoga.entity.Course;
import com.example.yoga.entity.CourseMv;
import com.example.yoga.entity.Mv;
import com.example.yoga.service.ICourseMvService;
import com.example.yoga.service.IMvService;
import com.example.yoga.util.JsonResult;
import com.example.yoga.util.PageDataResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liwenkai
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/mv")
public class MvController {

    @Autowired
    private IMvService mvService;

    @Autowired
    private ICourseMvService courseMvService;

    /**
     * 获取所有视频 getAllMv
     * @return
     */
    @RequestMapping("/getAllMv")
    public JsonResult<List> getAllMv(){
        List<Mv> mvList = mvService.list();
        if (mvList.size()>0){
            return new JsonResult<>(2000,mvList) ;
        }else{
            return new JsonResult<>(4000,"没有视频") ;
        }
    }

    /**
     * 查询所有视频
     */
    @RequestMapping("/queryMvAll")
    public PageDataResult queryMvAll(Integer pageIndex,Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        List<Mv> mvList = mvService.list();
        PageInfo<Mv> pageInfo = new PageInfo<Mv>(mvList);
        PageDataResult pdr = new PageDataResult();
        pdr.setList(pageInfo.getList());
        pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        return pdr;
//       if (mvList.size()>0){
//           return new JsonResult<>(2000,mvList);
//       }
//       return new JsonResult<>(4000,"没有视频信息");
    }

    /**
     * 根据课程Id查视频(查看某一课程下的所有视频)
     */
    @RequestMapping(value = "/queryMvByCourseId",method = RequestMethod.GET)
    public PageDataResult queryMvByCourseId(Integer id,Integer pageIndex, Integer pageSize){
        System.out.println("课程id"+id+"下的所有视频");
        //由于是关联表，所以应该借助course_mv表进行查询
        //1.先根据课程id从course_mv关联表中查出该课程下的所有视频id
        QueryWrapper<CourseMv> wrapper = new QueryWrapper<>();
        wrapper.eq("courseId",id);
        List<CourseMv> courseMvList = courseMvService.list(wrapper);
        //2.再将所有的视频取出来放到一个列表中
       // List<Mv> mvList = mvService.list();
        //3.创建一个新列表，将两个列表中的视频id比对，若是有相同的，放到新列表中，最后返回新列表，证明视频现在还存在
       // System.out.println(mvList);
        if (courseMvList.size()==0){
            return null;
        }
        //用第二种方法，根据courseMvList能够得到该课程下所有的mvid
        List<Integer> ids=new ArrayList<>();
        for (int i = 0; i < courseMvList.size(); i++) {
            ids.add(courseMvList.get(i).getMvid());
        }
        PageHelper.startPage(pageIndex,pageSize);
        QueryWrapper<Mv> mvQueryWrapper = new QueryWrapper<>();
        mvQueryWrapper.in("mvId",ids);
        List<Mv> list = mvService.list(mvQueryWrapper);
        PageInfo<Mv> pageInfo = new PageInfo<Mv>(list);
        PageDataResult pdr = new PageDataResult();
        pdr.setList(pageInfo.getList());
        pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
//
//        PageHelper.startPage(pageIndex,pageSize);
//        PageInfo<Mv> pageInfo = new PageInfo<Mv>(list);
//        PageDataResult pdr = new PageDataResult();
//        pdr.setList(pageInfo.getList());
//        pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        System.out.println("//////////////////////////////");
        System.out.println(pdr);
        return pdr;
    }
    public List<Mv> queryMvByCourseId2(List<CourseMv> courseMvList,  List<Mv> mvList){
        List<Mv> list = new ArrayList<>();
        for (int i = 0; i < courseMvList.size(); i++) {
            for (int j = 0; j < mvList.size(); j++) {
                //取出该课程下的第i个视频与视频列表进行遍历比较
                if(courseMvList.get(i).getMvid().equals(mvList.get(j).getMvid())){
                    //若是相等，则添加到新列表中
                    list.add(mvList.get(j));
                }
            }
        }
        return list;
    }


    /**
     * 根据视频名字查询视频
     */
    @RequestMapping("/queryMvByName")
    public PageDataResult queryMvByName(String name,Integer pageIndex,Integer pageSize){
        if (name==null||name.length()==0){
            return this.queryMvAll(pageIndex,pageSize);
        }
        QueryWrapper<Mv> wrapper = new QueryWrapper<>();
        wrapper.like("mvName",name);
        PageHelper.startPage(pageIndex,pageSize);
        List<Mv> mvList = mvService.list(wrapper);
        PageInfo<Mv> pageInfo = new PageInfo<Mv>(mvList);
        PageDataResult pdr = new PageDataResult();
        pdr.setList(pageInfo.getList());
        pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
       // System.out.println();
        return pdr;
//        if (mvList.size()>0){
//            return new JsonResult<>(2000,mvList);
//        }
//        return new JsonResult<>(4000,"无记录");
    }

    /**
     * 上传视频（增）
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String,String> upload(MultipartFile file)throws IllegalStateException{


        String savePaths="D:\\springboot-upload";
        //String webPaths="/images/";
        Map<String,String> resultMap = new HashMap<>();
        try{
            //获取文件后缀
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            String filename=file.getOriginalFilename();
            // 重构文件名称
            String pikId = UUID.randomUUID().toString().replaceAll("-", "");
            String newVidoeName = pikId +filename;
            //保存视频
            File fileSave = new File(savePaths, newVidoeName);
           // File fileSave = new File(savePaths, filename);
            file.transferTo(fileSave);
            Mv mv = new Mv();
           // mv.setMvname(filename);
            mv.setMvname(newVidoeName);
            mv.setMvpath(newVidoeName);
            mvService.save(mv);
            resultMap.put("resCode","1");
            resultMap.put("webShowPath",newVidoeName);
            return  resultMap;
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("resCode","0");
            return  resultMap ;
        }

    }
    /**
     * 删除单个视频(需要判断视频是否有关联课程)
     */
    @RequestMapping(value = "/del",method = RequestMethod.DELETE)
    public JsonResult<Void> delMv(Integer id){
        //根据mvid判断视频课程关联表中是否有记录
        QueryWrapper<CourseMv> wrapper = new QueryWrapper<>();
        wrapper.eq("mvId",id);
        //得到所有与视频关联的记录
        List<CourseMv> list = courseMvService.list(wrapper);
        //判断list的size是否大于0
        if(list.size()>0){
            //则不能删除，删除失败
            return new JsonResult<>(3000,"该视频正在使用中,不能删除!");
        }
        //删除视频
        boolean b = mvService.removeById(id);
        if(b){
          return new JsonResult<>(2000,"删除成功！");
        }
        return new JsonResult<>(4000,"删除异常！");
    }

    /**
     * 批量删除视频
     */
    @RequestMapping(value = "/delMore",method = RequestMethod.POST)
    public JsonResult<Void> delMvMore(@RequestBody List<Integer> ids){
        if (!ObjectUtils.isEmpty(ids)){
            //为了减少数据库连接，取出所有的mvcourse关系表
            List<CourseMv> courseMvs = courseMvService.list();
            //遍历这个list,逐一比较
            for (int i = 0; i < courseMvs.size(); i++) {
                for (int j = 0; j < ids.size(); j++) {
                    if(ids.get(j).equals(courseMvs.get(i).getMvid())){
                        return new JsonResult<>(3000,"您选择的视频中存在使用中的视频，不能删除");
                    }
                }
            }
            //删除
            boolean b = mvService.removeByIds(ids);
            if (b){
                return new JsonResult<>(2000,"删除成功");
            }
        }
        return new JsonResult<>(4000,"请选择要删除的视频！");
    }
    /**
     * 修改视频
     */
    @RequestMapping("/updateMv")
    public JsonResult<Void> updateMv(@RequestBody Mv mv){
        System.out.println(mv+"********");
        Integer mvid = mv.getMvid();
        QueryWrapper<Mv> wrapper = new QueryWrapper<>();
        wrapper.eq("mvId",mvid);
        boolean b = mvService.update(mv, wrapper);
        if(b){
            return new JsonResult<>(2000,"修改成功！");
        }
        return new JsonResult<>(4000,"修改失败！");
    }
}

